
#include <stdio.h>
#include <unistd.h>
#include <pthread.h>

typedef struct
{
    int res;
    int flag;
    pthread_cond_t cond;
    pthread_mutex_t mutex;
} Result;

void *set_fn(void *arg)
{
    int i = 1, sum = 0;
    for (; i <= 100; ++i)
    {
        sum += i;
    }

    Result *s = (Result *)arg;

    pthread_mutex_lock(&s->mutex);
    while (s->flag)
    {
        pthread_mutex_unlock(&s->mutex);
        sleep(1);
        pthread_mutex_lock(&s->mutex);
    }
    s->res = sum;
    pthread_mutex_unlock(&s->mutex);

    pthread_cond_broadcast(&s->cond);

    return (void *)0;
}

void *get_fn(void *arg)
{
    Result *s = (Result *)arg;

    pthread_mutex_lock(&s->mutex);

    s->flag = 0;

    pthread_cond_wait(&s->cond, &s->mutex);

    pthread_mutex_unlock(&s->mutex);

    printf("Result.res = %d\n", s->res);

    return (void *)0;
}

int main()
{
    Result res;

    res.flag = 1;
    pthread_cond_init(&res.cond, NULL);
    pthread_mutex_init(&res.mutex, NULL);

    pthread_t set, get;

    if (pthread_create(&set, NULL, set_fn, &res) != 0)
    {
        fprintf(stderr, "set pthread create error!\n");
    }

    if (pthread_create(&get, NULL, get_fn, &res) != 0)
    {
        fprintf(stderr, "get pthread create error!\n");
    }

    pthread_join(set, NULL);
    pthread_join(get, NULL);

    return 0;
}